#include "win/local.h"

namespace win
{
    LocalCache::LocalCache()
    {
        Gdiplus::GdiplusStartup( &m_pGdiToken, &m_gdiplusStartupInput, NULL );
        Initialize();
    }

    LocalCache::~LocalCache()
    {
        Gdiplus::GdiplusShutdown( m_pGdiToken );
    }

    void LocalCache::Initialize()
    {
        CString strPath;
        GetModuleFileName( NULL, strPath.GetBufferSetLength( MAX_PATH + 1 ), MAX_PATH );
        strPath.ReleaseBuffer();
        int nPos = strPath.ReverseFind('\\');
        if( nPos != -1 )
        {
            strPath = strPath.Left( nPos );
        }

        m_strWorkspace = strPath;
        m_strWorkspace.Append( _T("\\res\\") );
    }

    BOOL LocalCache::GetBinaryResource( LPCTSTR lpszFile, BYTE ** pBuffer, DWORD *dwSize, BOOL bCache )
    {
        if( !lpszFile || !pBuffer )
        {
            return FALSE;
        }

        CString strFile = m_strWorkspace + lpszFile;
        *pBuffer = 0;
        if( dwSize )
            *dwSize = 0;

        __int64 i64Size = 0;
        DWORD   dwReadSize = 0;
        if( WinFile::GetFileSize( strFile, &i64Size ) && i64Size > 0 )
        {
            *pBuffer = new BYTE[ (unsigned)i64Size ];
            if( *pBuffer )
            {
                memset( *pBuffer, 0, (size_t)i64Size );
                dwReadSize = (DWORD)i64Size;
            }
            else
                return FALSE;

            if( !WinFile::ReadFile( strFile, *pBuffer, dwReadSize ) )
            {
                delete[] *pBuffer;
                *pBuffer = 0;
                return FALSE;
            }
            else
            {
                if( dwSize )
                    *dwSize = dwReadSize;

                return TRUE;
            }
        }

        return FALSE;
    }

    BOOL LocalCache::GetImage( LPCTSTR lpszFile, Image* winImage, BOOL bCache )
    {
        if( !lpszFile || !*lpszFile )
        {
            return FALSE;
        }

        if( bCache )
        {
            _imgcache::iterator iter = m_mapCache.find( lpszFile );
            if( iter != m_mapCache.end() )
            {
                winImage->Copy(iter->second);
                return TRUE;
            }
        }

        CString strPath = m_strWorkspace + lpszFile;

        Gdiplus::Image * pImage = Gdiplus::Image::FromFile( strPath );
        if( !pImage )
        {
            return FALSE;
        }

        BOOL bCreate = winImage->CreateFromImage( pImage );
        delete pImage;

        if( bCreate )
        {
            Image *pWinImage = new Image;
            if( pWinImage )
            {
                pWinImage->Copy( winImage );
                m_mapCache[ lpszFile ] = pWinImage;
            }

            return TRUE;
        }

        return FALSE;
    }
}